package com.xh.mybatisplus.controller;

import com.xh.mybatisplus.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @program: xh-learn-record
 * @description:
 * @author: sch
 * @create: 2023-02-28 16:34
 **/
@RestController
@RequestMapping("redis02test")
public class RedisTestController {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("get")
    public String get(String str) {
        return (String) redisUtil.get(str);
    }

    @RequestMapping("set")
    public String get(String str, String val) {
        redisUtil.set(str, val);
        return "okk";
    }


    @RequestMapping("limiter")
    public String limiter() {
        //当前时间作为key 精到秒
        int second = LocalDateTime.now().getSecond();
        String key = "stock" + second;
        Object o = redisUtil.get(key);
        if (Objects.isNull(o)) {
            redisUtil.set(key, String.valueOf(1));
            redisUtil.expire(key, 2000);
        } else {
            int count = (int) redisUtil.get(key);
            if (count > 10) {
                return "限流了";
            } else {
                redisUtil.set(second + "", String.valueOf(count));
                redisUtil.expire(key, 2000);
            }
        }


        return "ok";
    }

    @RequestMapping("limiter2")
    public String limiter2() {
        String key = "goodStock_" + LocalDateTime.now().getSecond();
        Long count = redisTemplate.opsForValue().increment(key);
        if (count == 1) {
            redisTemplate.expire(key, 1L, TimeUnit.SECONDS);
        }
        if (count > 10) {
            return "限流";
        }
        return "ok";

    }

    public static void main(String[] args) {
        System.out.println(LocalDateTime.now().getSecond());
        System.out.println(Calendar.getInstance().get(Calendar.SECOND));
        System.out.println(System.currentTimeMillis() / 1000);
    }
}
